# coding: utf-8

from flask import Flask, url_for
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_uploads import UploadSet, configure_uploads, IMAGES
from flask_babelex import Babel

from config import config

bootstrap = Bootstrap()
db = SQLAlchemy()
photos = UploadSet('photos', IMAGES)


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    db.init_app(app)

    app.add_url_rule('/_uploads/photos/<path:filename>', endpoint='images', build_only=True)

    @app.route('/images')
    def images():
        return url_for('images', filename=None)
    configure_uploads(app, photos)
    from .admin import admin

    admin.init_app(app)

    # 附加路由和自定义的错误页面
    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    babel = Babel(app)
    app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'

    return app